//引入node内置模块,无需下载,直接引入
const path = require("path");

//处理html的插件
const HtmlWebpackPlugin = require("html-webpack-plugin");

//提取css插件
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

//压缩css
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");

//# 引入
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

//引入glob
let glob = require("glob");
let files = glob.sync("./src/pages/*?/*?.js");
let entry = {};
files.forEach(function (v) {
  let fn = v.match(/\/(\w+)\.js/i);
  entry[fn[1]] = v;
});

let htmls = glob.sync("./src/pages/*?/*?.html");
let htmlArr = htmls.map(function (v) {
  let fn = v.match(/\/(\w+)\.html/i);
  return new HtmlWebpackPlugin({
    template: v,
    filename: fn[0].substr(1),
    chunks: [fn[1]],
  });
});

console.log(htmlArr);

//暴露webpack对象
module.exports = {
  //入口entry
  entry: entry,

  //出口output
  output: {
    path: path.resolve(__dirname, "dist"), //出口路径
    filename: "js/[name]-[hash:5].js", //输出文件名字, //输出文件名字
    publicPath: "./",
  },

  //加载器loader
  module: {
    rules: [
      //css
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: "../",
            },
          },
          "css-loader",
        ], //顺序不能换
      },
      //less
      {
        test: /\.less$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: "../",
            },
          },
          "css-loader",
          "less-loader",
        ],
      },
      //背景图
      {
        test: /\.(jpg|png|gif|jpeg)$/,
        loader: "url-loader",
        options: {
          name: "[hash:16].[ext]", // 图片输出的名字hash长度16位 默认32位
          limit: 10 * 1024, // 小于10kb base64处理
          outputPath: "imgs", //输出路径
          esModule: false, //关闭es6模块化
        },
        type: "javascript/auto",
      },
      //打包html中的图片文件
      {
        test: /\.html$/, // 处理html中引入img
        loader: "html-loader",
      },

      //字体图标
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/, // 处理字体格式文件
        type: "asset/resource",
        generator: {
          filename: "fonts/[name].[hash:6][ext]",
        },
      },
    ],
  },

  //插件plugins
  plugins: [
    // 提取css
    new MiniCssExtractPlugin({
      filename: "css/[name]-[hash:5].css", // 重命名输出的css
    }),

    // 压缩css
    new OptimizeCssAssetsWebpackPlugin(),

    // 删除dist目录
    new CleanWebpackPlugin(),

    //合并数组
    ...htmlArr,
  ],

  // 开发服务器 -- 和五大特性同级
  devServer: {
    contentBase: path.resolve(__dirname, "dist"), //启动服务器目录
    publicPath: "/", // 静态资源查找路径
    compress: true, // 启动gzip
    port: 9527, // 端口
    open: true, // 是否在浏览器自动打开
    openPage: ["ad.html"], //默认打开页面
  },
  target: "web", // 目标是浏览器

  //模式mode
  //development: 开发模式
  //production: 生产模式  线上使用===极致压缩
  mode: process.env.NODE_ENV, //开发模式
};
